package control;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.bean.aluguel;
import model.bean.livro;
import model.dao.AluguelDao;
import model.dao.LivroDao;

/**
 * Servlet implementation class ServletUsuario
 */
@WebServlet("/Aluguel")
public class ServletAluguel extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletAluguel() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		int acao=Integer.parseInt(request.getParameter("acao"));
		int id = Integer.parseInt(request.getParameter("id"));
		int idlivro = Integer.parseInt(request.getParameter("idlivro"));
		
		if(acao == 0){
			aluguel obj = new aluguel();
			AluguelDao dao = new AluguelDao();
			obj = (aluguel) dao.findById(obj, id);			
			obj.setDataDevolucao(new Date());						

			dao.update(obj);
			
			LivroDao daoL = new LivroDao();
			daoL.qtdMais(idlivro);
			
		}
		String urlRetorno = request.getHeader("referer");
		urlRetorno = urlRetorno.replace("?", ";");
		String[] urls = urlRetorno.contains(";") ? urlRetorno.split(";") : null;
		if(urls != null && urls.length > 0){
			response.sendRedirect(urls[0] + "?content=7");
		}else{
			response.sendRedirect(urlRetorno + "?content=7");
		}
	}
}
